package org.carshared.principal;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.carshared.R;
import org.carshared.sqlite.DBAdapterDateTravel;
import org.carshared.sqlite.DBAdapterPassenger;
import org.carshared.sqlite.DBAdapterTravel;
import org.carshared.utils.Lista_adaptador;
import org.carshared.utils.PassengerBeen;
import org.carshared.utils.TravelBeen;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class TraveList extends Fragment {

	private ListView lista;
	ArrayList<TravelBeen> datos;
	private String user;
	private boolean dialogExecuted = false;

	protected static final int EDITTRAVEL = 2;
	private boolean activityPassed = false;
	private DecimalFormat df;
	private TravelBeen elegido;
	private Object mActionMode;
	private DBAdapterTravel dbHelper;
	private DBAdapterPassenger dbHelperPassenger;
	private DBAdapterDateTravel dbHelperDateTravel;
	private View myView;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		myView = inflater.inflate(R.layout.fragment_list, null);

		user = getArguments().getString("user");
		datos = new ArrayList<TravelBeen>();
		df = new DecimalFormat("#.##");

		dbHelper = new DBAdapterTravel(getActivity());
		dbHelperPassenger = new DBAdapterPassenger(getActivity());
		dbHelperDateTravel = new DBAdapterDateTravel(getActivity());
		getTravels();
		setLista(myView);

		lista.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> pariente, View view,
					int posicion, long id) {
				TravelBeen elegido = (TravelBeen) pariente
						.getItemAtPosition(posicion);
				activityPassed = true;

				Intent i = new Intent(getActivity(), CalendarActivity.class);
				Gson gson = new Gson();
				i.putExtra("dataTravel", gson.toJson(elegido));
				i.putExtra("user", user);
				startActivity(i);

			}

		});

		lista.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> pariente, View view,
					int posicion, long id) {
				elegido = (TravelBeen) pariente.getItemAtPosition(posicion);
				if (mActionMode != null) {
					return false;
				}
				view.setSelected(true);
				// Start the CAB using the ActionMode.Callback defined above

				mActionMode = getActivity()
						.startActionMode(mActionModeCallback);

				return true;

			}

		});

		return myView;
	}

	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

		// Called when the action mode is created; startActionMode() was called
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// Inflate a menu resource providing context menu items

			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate(R.menu.modal, menu);
			return true;
		}

		// Called each time the action mode is shown. Always called after
		// onCreateActionMode, but
		// may be called multiple times if the mode is invalidated.
		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false; // Return false if nothing is done
		}

		// Called when the user selects a contextual menu item
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			Intent i;
			Gson gson;
			switch (item.getItemId()) {

			case R.id.discard:

				Toast.makeText(getActivity().getApplicationContext(), "Delete",
						Toast.LENGTH_SHORT).show();

				dbHelperPassenger.deletePassenger(elegido.getOrigenDestino());
				dbHelperDateTravel.deleteAll(elegido.getOrigenDestino());
				dbHelper.deleteTravel(elegido.getOrigenDestino());
				// Actualizamos la lista
				getTravels();
				setLista(myView);

				mode.finish(); // Action picked, so close

				return true;
			case R.id.edit:

				i = new Intent(getActivity(), EditTravelActivity.class);
				gson = new Gson();
				i.putExtra("dataTravel", gson.toJson(elegido));
				startActivityForResult(i, EDITTRAVEL);

				Toast.makeText(getActivity().getApplicationContext(), "Edit",
						Toast.LENGTH_SHORT).show();
				mode.finish();
				return true;

			case R.id.inform:

				i = new Intent(getActivity(), InformActivity.class);
				gson = new Gson();
				i.putExtra("dataTravel", gson.toJson(elegido));
				startActivity(i);

				mode.finish();
				return true;

			default:
				mode.finish();
				return false;

			}
		}

		// Called when the user exits the action mode
		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mActionMode = null;
		}
	};

	private void getTravels() {
		// TODO Auto-generated method stub
		datos = dbHelper.fetchAllTravel(user);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void createTravel(TravelBeen t) {
		// TODO Auto-generated method stub

		// Crear viaje
		if (dbHelper.createTravel(t) == -1) {
			Toast.makeText(getActivity().getApplicationContext(),
					"ERROR, Registro no guardado..", Toast.LENGTH_LONG).show();
		}

	}

	private void createPassenger(TravelBeen t) {
		// TODO Auto-generated method stub
		for (PassengerBeen p : t.getListaPasajeros()) {
			dbHelperPassenger.createPassenger(p);
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub

		// if (dialogExecuted == true || activityPassed == true) {
		// if (activityPassed == true) {
		getTravels();
		// }
		setLista(myView);
		// }

		super.onResume();
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onContextItemSelected(item);

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	public void setLista(View myView) {
		lista = (ListView) myView.findViewById(R.id.ListView_listado_detail);
		if (datos.isEmpty()) {
			TravelBeen vacia = new TravelBeen(0, getResources().getString(
					R.string.Vacia), 0, "", 0, 0, 0, 0, null, 0, "");

			datos.add(vacia);
		}
		lista.setAdapter(new Lista_adaptador(getActivity(), R.layout.list_item,
				datos) {
			@Override
			public void onEntrada(Object entrada, View view) {
				if (entrada != null) {
					if (datos.get(0).getId() == 0) {
						ImageView imagen = (ImageView) view.findViewById(R.id.imageView_imagen);
						ImageView imagen2 = (ImageView) view.findViewById(R.id.flecha);
						imagen.setVisibility(View.INVISIBLE);
						imagen2.setVisibility(View.INVISIBLE);
						view.setClickable(false);
					}else{
						TextView texto_inferior_entrada = (TextView) view
								.findViewById(R.id.acumulado);
						if (texto_inferior_entrada != null)
							texto_inferior_entrada.setText(df
									.format((((TravelBeen) entrada)
											.getAcumulado())));
					}
					TextView texto_superior_entrada = (TextView) view
							.findViewById(R.id.destino);
					if (texto_superior_entrada != null)
						texto_superior_entrada.setText(((TravelBeen) entrada)
								.getOrigenDestino());

					
						
					
				}
			}

		});
	}
}
